package thinker.miracle.business.user.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import thinker.miracle.business.user.dao.UserInfoDao;
import thinker.miracle.business.user.entity.UserInfoEntity;
import thinker.miracle.business.user.entity.UserLoginLogEntity;

/**
 * @author bo.chen
 *
 */
@Service
public class UserInfoService {
	
	@Autowired
	UserInfoDao userInfoDao;
	
	@Autowired
	UserLoginLogService userLoginLogService;

	/**
	 * 保存用户 信息
	 * 
	 * @param userInfoEntity
	 */
	@Transactional
	public void save(UserInfoEntity userInfoEntity) {
		if(userInfoEntity != null && userInfoEntity.getId() != null){
			userInfoDao.updateSelective(userInfoEntity);
		}else if(userInfoEntity != null && userInfoEntity.getId() == null){
			userInfoDao.insert(userInfoEntity);
		}else{
			throw new RuntimeException("user save exception");
		}
	}

	/**
	 * 根据手机号码查询用户
	 * 
	 * @param phone
	 * @return
	 */
	public UserInfoEntity getByPhone(String phone) {
		List<UserInfoEntity> userInfos = userInfoDao.findByPhone(phone);
		if(userInfos != null && userInfos.size() == 1){
			return userInfos.get(0);
		}
		return null;
	}

	/**
	 * 手机号码登陆验证
	 * 
	 * @param phone
	 * @param password
	 * @return
	 */
	public UserInfoEntity loginVerify(String phone, String password) {
		List<UserInfoEntity> userInfos = userInfoDao.findByPhoneAndPassword(phone, password);
		if(userInfos != null && userInfos.size() == 1){
			return userInfos.get(0);
		}
		return null;
	}

	/**
	 * tocken验证
	 * 
	 * @param tocken
	 * @return
	 */
	public boolean verifyTocken(String tocken) {
		UserLoginLogEntity userLoginLogs = userLoginLogService.getByTocken(tocken);
		return userLoginLogs != null;
	}

	/**
	 * 根据tocken查询用户信息
	 * 
	 * @param tocken
	 * @return
	 */
	public UserInfoEntity getByTocken(String tocken) {
		UserLoginLogEntity userLoginLog = userLoginLogService.getByTocken(tocken);
		if(userLoginLog != null && userLoginLog.getId() != null){
			return getById(userLoginLog.getUserId());
		}
		return null;
	}

	/**
	 * 根据id获取用户信息
	 * 
	 * @param id
	 * @return
	 */
	public UserInfoEntity getById(String id) {
		List<UserInfoEntity> userInfos = userInfoDao.findById(id);
		if(userInfos != null && userInfos.size()==1){
			return userInfos.get(0);
		}
		return null;
	}
}
